package com.example.study.validator;

import lombok.SneakyThrows;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CheckTimeIntervalValidator implements ConstraintValidator<CheckTimeInterval, Object> {

    private String startTime;
    private String endTime;
    private String format;

    @Override
    public void initialize(CheckTimeInterval constraintAnnotation) {
        this.startTime = constraintAnnotation.startTime();
        this.endTime = constraintAnnotation.endTime();
        this.format = constraintAnnotation.format();
    }

    @SneakyThrows
    @Override
    public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
        if (null == object){
            return true;
        }

        BeanWrapper beanWrapper = new BeanWrapperImpl(object);
        Object start = beanWrapper.getPropertyValue(startTime);
        Object end = beanWrapper.getPropertyValue(endTime);

        if (null == start || null == end){
            return true;
        }

        DateFormat dateFormat = new SimpleDateFormat(format);
        Date startDate;
        Date endDate;

        try {
            startDate = dateFormat.parse(start.toString());
        }catch (ParseException parseException){
            throw new ParseException(startTime + "的格式不正确，正确格式" + format, 0);
        }

        try {
            endDate = dateFormat.parse(end.toString());
        }catch (ParseException parseException){
            throw new ParseException(endTime + "的格式不正确，正确格式" + format, 0);
        }

        int result = endDate.compareTo(startDate);
        return result >= 0;
    }
}
